/*
state = ['a', 'b']
action :
{type: "add", payload: "text"}
{type: "remove", payload: index}
{type: "clear", }
*/
// arr = ['a', 'b', 'c']
// index = 2
// function remove(arr, index) {
//   return arr.filter((_, i) => i!==index)
// }

import { useReducer } from 'react'

const reducer = (state, action) => {
  switch (action.type) {
    case 'add':
      return [...state, action.payload]
    case 'remove':
      return state.filter((_, i) => i !== action.payload)
    case 'clear':
      return []
    default:
      return state
  }
}
// console.log(
//   reducer(['x'], {type: 'add', payload: 'b'})
// ) // ['x', 'b']
// console.log(reducer(['a', 'b', 'c'], {
//   type: 'remove', payload: 1
// })) // ['a', 'c']
// console.log(reducer(['a', 'b', 'c'], {
//   type: 'clear'
// })) // []

const ListReducerDemo = () => {
  const [state, dispatch] = useReducer(reducer, ['初始值'])
  const [state2, dispatch2] = useReducer(reducer, ['a', 'b'])
  console.log(state)
  return (
    <>
      <button
        onClick={() => {
          dispatch({ type: 'add', payload: Math.random() })
        }}
      >
        添加
      </button>
      <button
        onClick={() => {
          dispatch({ type: 'clear' })
        }}
      >
        清空
      </button>
      <ul>
        {state.map((n, index) => (
          <li
            key={index}
            onClick={() => dispatch({ type: 'remove', payload: index })}
          >
            {n}
          </li>
        ))}
      </ul>
      {/** ------- */}
      <button
        onClick={() => {
          dispatch2({ type: 'add', payload: Math.random() })
        }}
      >
        添加
      </button>
      <button
        onClick={() => {
          dispatch2({ type: 'clear' })
        }}
      >
        清空
      </button>
      <ul>
        {state2.map((n, index) => (
          <li
            key={index}
            onClick={() => dispatch2({ type: 'remove', payload: index })}
          >
            {n}
          </li>
        ))}
      </ul>
    </>
  )
}

export default ListReducerDemo
